<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Authors extends BaseModel
{
    use HasFactory;

    const CREATED_AT='create_time';
    const UPDATED_AT='change_time';

    protected $table = 'authors';

    public function __construct()
    {
        parent::__construct();



    }

     /**
     *  作者添加
     * @param $data 添加的数据
     */
    public function add($data, $field = []){

        $this->username = $data->username;
        $this->username_en = $data->username_en;
        $this->birthday = $data->birthday;
        $this->sex = $data->sex;
        if(!empty($data->img)) $this->img = $data->img;
        $this->intro = $data->intro;
        $this->intro_en = $data->intro_en;
        $this->is_del = 1;

        return  $this->save();
    }

    /**
     * 作者修改
     * @param $data 添加的数据
     */
    public function change($data, $field = [], $findWhere = []){
        $res = $this->where('is_del' , 1)->find($data['id']);
        if(!$res){
            throw new Exception('数据获取失败');
        }

        $res->username = $data->username;
        $res->username_en = $data->username_en;
        $res->birthday = $data->birthday;
        $res->sex = $data->sex;
        if(!empty($data->img)) $res->img = $data->img;
        $res->intro = $data->intro;
        $res->intro_en = $data->intro_en;

        return  $res->save();
    }


    /**
     * 判断作者名称是否已经存在
     * @param username 作者名称
     * @param id 作者id   可选，主要是用于修改
     */
    public function authorNameIsExists($username , $id = null){
        $res = $this->where('username' , $username)->where(function($query) use($id){
                if(!empty($id)){
                    $query->where('id' , '<>' , $id);
                }
        })->where('is_del' , 1)->first();
        return $res;
    }

}
